package com.sky.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.context.BaseContext;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.ISetmealService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 套餐 服务实现类
 * </p>
 *
 * @author fcy
 * @since 2025-09-08
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements ISetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishMapper dishMapper;
    /**
     * 新增套餐
     * @param setmealDTO
     */
    @Override
    public void add(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);
        // 防止前端传入 id 影响自增策略
        setmeal.setId(null);
        setmeal.setCreateTime(LocalDateTime.now());
        setmeal.setUpdateTime(LocalDateTime.now());
        setmeal.setCreateUser(BaseContext.getCurrentId());
        setmeal.setUpdateUser(BaseContext.getCurrentId());
        this.save(setmeal);
        // 使用数据库生成的主键
        Long id = setmeal.getId();
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.forEach(setmealDish->{
            setmealDish.setSetmealId(id);
            setmealDishMapper.insert(setmealDish);
        });

    }
    /**
     * 套餐分页查询
     * @param setmealPageQueryDTO
     * @return
     */
    @Override
    public Result<PageResult> pageQuery(SetmealPageQueryDTO setmealPageQueryDTO) {
        Page<Setmeal> page = new Page<>(setmealPageQueryDTO.getPage(),setmealPageQueryDTO.getPageSize());
        lambdaQuery()
                .like(setmealPageQueryDTO.getName()!=null,Setmeal::getName, setmealPageQueryDTO.getName())
                .eq(setmealPageQueryDTO.getCategoryId()!=null ,Setmeal::getCategoryId, setmealPageQueryDTO.getCategoryId())
                .eq( setmealPageQueryDTO.getStatus()!=null,Setmeal::getStatus, setmealPageQueryDTO.getStatus())
                .page(page);
        List<SetmealVO> VOList = new ArrayList<>();
        page.getRecords().forEach(setmeal -> {
            SetmealVO vo = new SetmealVO();
            BeanUtils.copyProperties(setmeal,vo);
            Category category = categoryMapper.selectById(setmeal.getCategoryId());
            vo.setCategoryName(category.getName());
            VOList.add(vo);
        });
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(VOList);
        return Result.success(pageResult);
    }
    /**
     * 批量删除套餐
     * @param ids
     */
    @Override
    public void deleteByIds(List<Long> ids) {
        ids.forEach(id->{
            if(this.getById(id).getStatus()==1){
                throw new RuntimeException("套餐正在售卖中，不能删除");
            }
            setmealMapper.deleteById( id);
            setmealDishMapper.delete(new QueryWrapper<SetmealDish>().eq("setmeal_id",id));
        });
    }
    /**
     * 套餐起售停售
     * @param status
     * @param id
     */
    @Override
    public Result<String> changeStatus(Integer status, Long id) {
        QueryWrapper<SetmealDish> wrapper = new QueryWrapper<SetmealDish>()
                .eq("setmeal_id", id);
        List<SetmealDish> setmealDishes = setmealDishMapper.selectList(wrapper);
        List< Long> dishIds = new ArrayList<>();
        setmealDishes.forEach(setmealDish -> {
            dishIds.add(setmealDish.getDishId());
        });
        dishIds.forEach(dishId->{
            if(dishMapper.selectById(dishId).getStatus()==0&&status==1){
               throw new RuntimeException("关联的菜品正在停售中");
            }
        });
        Setmeal setmeal = new Setmeal();
        setmeal.setId(id);
        setmeal.setStatus(status);
        this.updateById(setmeal);
        return Result.success();

    }
    /**
     * 根据id查询套餐
     * @param id
     * @return
     */
    @Override
    public Result<SetmealVO> selectById(Long id) {
        Setmeal setmeal = this.getById(id);
        SetmealVO vo = new SetmealVO();
        BeanUtils.copyProperties(setmeal,vo);
        vo.setCategoryName(categoryMapper.selectById(setmeal.getCategoryId()).getName());
        vo.setSetmealDishes(setmealDishMapper.selectList(new QueryWrapper<SetmealDish>().eq("setmeal_id",id)));
        return Result.success(vo);
    }
    /**
     * 修改套餐
     * @param setmealDTO
     */
    @Override
    public void change(SetmealDTO setmealDTO) {
        Long id = setmealDTO.getId();
        Setmeal setmeal = this.getById(id);
        BeanUtils.copyProperties(setmealDTO,setmeal);
        setmeal.setUpdateTime(LocalDateTime.now());
        setmeal.setUpdateUser(BaseContext.getCurrentId());
        this.updateById(setmeal);
        QueryWrapper<SetmealDish> wrapper = new QueryWrapper<SetmealDish>()
                .eq("setmeal_id", id);
        List<SetmealDish> setmealDishes = setmealDishMapper.selectList(wrapper);
        setmealDishes.forEach(setmealDish -> {
            setmealDishMapper.deleteById(setmealDish.getId());
        });
        List<SetmealDish> dishes = setmealDTO.getSetmealDishes();
        dishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(id);
            setmealDishMapper.insert(setmealDish);
        });

    }
    /**
     * 获取用户端套餐列表
     * @param categoryId
     * @return
     */
    @Override
    public Result<List<Setmeal>> getUserList(Integer categoryId) {
        List<Setmeal> list = lambdaQuery()
                .eq(Setmeal::getCategoryId, categoryId)
                .eq(Setmeal::getStatus, 1)
                .list();
        return Result.success(list);
    }
}
